package com.game.business.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.game.business.domain.*;
import com.game.business.service.*;
import com.game.common.annotation.Anonymous;
import com.game.common.annotation.RepeatSubmit;
import com.game.common.core.controller.BaseController;
import com.game.common.core.domain.AjaxResult;
import com.game.common.core.domain.entity.SysDictData;
import com.game.common.core.domain.entity.SysUser;
import com.game.common.core.domain.entity.SysUserPhone;
import com.game.common.core.page.TableDataInfo;
import com.game.common.exception.ServiceException;
import com.game.common.utils.*;
import com.game.system.domain.SysNotice;
import com.game.system.service.ISysDictDataService;
import com.game.system.service.ISysNoticeService;
import com.game.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;


/**
 * 接口
 */
@RestController
@RequestMapping("/webApi")
public class ApiController extends BaseController {

    @Autowired
    private YzCodeUtils yzCodeUtils;

    @Autowired
    private ITTxSqService txSqService;

    @Autowired
    private ITWalletService tWalletService;

    @Autowired
    private ITConfigService configService;


    @Autowired
    private ITOrderService tOrderService;


    @Autowired
    private ITGameService gameService;
    @Autowired
    private ITGameRwService gameRwService;

    @Autowired
    private ITGameQfService gameQfService;
    @Autowired
    private ISysDictDataService iSysDictDataService;
    @Autowired
    private ISysNoticeService noticeService;

    @Autowired
    private IGroupMemberService groupMemberService;

    /**
     * 查询系统配置列表
     */
    @Anonymous
    @GetMapping("/configlist")
    public AjaxResult list(TConfig tConfig) {
        List<TConfig> list = configService.selectTConfigList(tConfig);
        return AjaxResult.success(list);

    }

    /**
     * 查询数据字典
     */
    @Anonymous
    @GetMapping("/getDict")
    public AjaxResult getDict(String key) {
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(key);
        List<SysDictData> dictCache = iSysDictDataService.selectDictDataList(sysDictData);
        return AjaxResult.success(dictCache);
    }

    @Autowired
    private ITLbImageService lbImageService;

    /**
     * 查询banner图管理列表
     */
    @Anonymous
    @GetMapping("/imagelist")
    public AjaxResult imagelist() {
        List<TLbImage> list = lbImageService.selectTLbImageList(new TLbImage());
        return AjaxResult.success(list);
    }


    /**
     * 查询任务类型
     */
    @GetMapping("/gametwlist")
    @Anonymous
    public AjaxResult gametwlist(TGameRw tGameRw) {
        startPage();
        List<TGameRw> list = gameRwService.selectTGameRwList(tGameRw);
        return AjaxResult.success(list);
    }

    @Autowired
    private ITGameQfService tGameQfService;


    @Autowired
    ISysUserService sysUserService;


    @Autowired
    private ITOrderDbrRecordService orderDbrRecordService;


    /**
     * 查询用户列表（担保人）分页
     */
    @GetMapping("/getUserList")
    public TableDataInfo getUserList(SysUser tUser) {
        startPage();
        String groupId = tUser.getGroupId();
        if(StringUtils.isNotEmpty(groupId)){
            // 群聊Id 需要排除已经在群的用户
            GroupMember  groupMember = new GroupMember();
            groupMember.setGroupId(groupId);
            List<GroupMember> groupMemberList = groupMemberService.selectGroupMemberList(groupMember);
            // 获取groupMemberList 中 userId
            List<String> userIdList = groupMemberList.stream().map(GroupMember::getUserId).collect(Collectors.toList());
            tUser.setNotUserIds(userIdList);
        }
        List<SysUser> list = sysUserService.selectUserListApp(tUser);
        return getDataTable(list);
    }

    @GetMapping("/getUserListNoPage")
    public AjaxResult getUserListNoPage(SysUser tUser) {
        String groupId = tUser.getGroupId();
        if(StringUtils.isNotEmpty(groupId)){
            // 群聊Id 需要排除已经在群的用户
            GroupMember  groupMember = new GroupMember();
            groupMember.setGroupId(groupId);
            List<GroupMember> groupMemberList = groupMemberService.selectGroupMemberList(groupMember);
            // 获取groupMemberList 中 userId
            List<String> userIdList = groupMemberList.stream().map(GroupMember::getUserId).collect(Collectors.toList());
            tUser.setNotUserIds(userIdList);
        }
        List<SysUser> list = sysUserService.selectUserListApp(tUser);
        return AjaxResult.success(list);
    }


    /**
     * 查询游戏区服列表
     */
    @Anonymous
    @GetMapping("/gameQflist")
    public AjaxResult gameQflist(TGameQf tGameQf) {
        List<TGameQf> list = tGameQfService.selectTGameQfList(tGameQf);
        return AjaxResult.success(list);
    }


    /**
     * 获取通知公告列表(分页)
     */
    @Anonymous
    @GetMapping("/noticelist")
    public TableDataInfo noticelist(SysNotice notice) {
        startPage();
        List<SysNotice> list = noticeService.selectNoticeList(notice);
        return getDataTable(list);
    }

    /**
     * 通知详细信息
     */
    @GetMapping(value = "/noticeDetail/{noticeId}")
    public AjaxResult noticeDetail(@PathVariable Long noticeId)
    {
        SysNotice sysNotice = noticeService.selectNoticeById(noticeId);
        return success(sysNotice);
    }



    /**
     * 查询游戏列表
     */
    @Anonymous
    @GetMapping("/gamelist")
    public AjaxResult gamelist(TGame tGame) {
        List<TGame> list = gameService.selectTGameList(tGame);
        return AjaxResult.success(list);
    }

    /**
     * 创建发布订单
     */
    @Transactional
    @PostMapping("/addOrder")
    public AjaxResult addOrder(@RequestBody TOrder tOrder) {
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        String orderNumber = String.valueOf(snowflake.nextId());
        tOrder.setOrderNo(orderNumber);
        tOrder.setUserId(SecurityUtils.getUserIdStr());
        tOrder.setOrderStatus("1");
        String userCouponId = tOrder.getUserCouponId();
        if (!StringUtils.isEmpty(userCouponId)) {
            TCouponUser coupon = couponUserService.getById(userCouponId);
            tOrder.setCouponId(coupon.getCouponId());
            // 更新优惠券状态
            TCouponUser couponUser = new TCouponUser();
            couponUser.setId(userCouponId);
            couponUser.setStatus("1");
            couponUser.setUseTime(DateUtils.getNowDate());// 假设"1"表示已使用
            couponUserService.updateTCouponUser(couponUser);
        }
        if (tOrder.getCouponPrice() != null) {
            tOrder.setPrice(tOrder.getOrderPrice().subtract(tOrder.getCouponPrice()));
        }
        tOrderService.save(tOrder);
        // 创建担保人
        if (StringUtils.isNotEmpty(tOrder.getDbrUserId())) {
            TOrderDbrRecord orderDbrRecord = new TOrderDbrRecord();
            orderDbrRecord.setOrderId(tOrder.getId());
            orderDbrRecord.setDbrUserId(tOrder.getDbrUserId());
            orderDbrRecord.setSource("1");
            orderDbrRecord.setType("1");
            orderDbrRecordService.save(orderDbrRecord);
        }
        if ("1".equals(tOrder.getType())) {
            //扣除用户余额、保存记录
            this.saveUserMoneyAndSubRecord(tOrder.getId(), tOrder.getOrderPrice().negate(), "1", SecurityUtils.getUserIdStr());
        }

        return AjaxResult.success(tOrder);
    }

    /**
     * 我的订单列表分页----发单人
     */
    @GetMapping("/getMyOrderlist")
    public TableDataInfo getMyOrderlist(TOrder tOrder) {
        startPage();
        tOrder.setUserId(SecurityUtils.getUserIdStr());
        List<TOrder> list = tOrderService.selectTOrderList(tOrder);
        return getDataTable(list);
    }


    /**
     * 订单列表分页
     */
    @Anonymous
    @GetMapping("/getOrderlist")
    public   TableDataInfo getOrderlist(TOrder tOrder) {
        startPage();
        tOrder.setStatus("1");
        String sfType = tOrder.getSfType();
        if("1".equals(sfType)){
            // 大厅 用户查询待接单的
            tOrder.setOrderStatus("1");
        }else if("2".equals(sfType)){
            //大厅 代练师
            // 查询待接单的状态
        }else if("3".equals(sfType)){
            // 担保人大厅 查询  （1）选择需要担保人还没有的担保人的 未完成订单
            //(2) 需要担保人介入的订单
            tOrder.setDbrUserDt("13243434");
        }
        List<TOrder> list = tOrderService.selectTOrderList(tOrder);
        return getDataTable(list);
    }


    /**
     * 我的订单列表分页---代练师
     */
    @GetMapping("/getMyOrderDlslist")
    public TableDataInfo getMyOrderDlslist(TOrder tOrder) {
        startPage();
        tOrder.setPlayUserId(SecurityUtils.getUserIdStr());
        tOrder.setStatus("1");
        List<TOrder> list = tOrderService.selectTOrderList(tOrder);
        return getDataTable(list);
    }


    /**
     * 我的订单列表分页---担保人
     */
    @GetMapping("/getMyOrderDbrlist")
    public TableDataInfo getMyOrderDbrlist(TOrder tOrder) {
        startPage();
        tOrder.setDbrUserId(SecurityUtils.getUserIdStr());
        tOrder.setStatus("1");
        List<TOrder> list = tOrderService.selectTOrderList(tOrder);
        return getDataTable(list);
    }


    /**
     * 订单详情
     */
    @Anonymous
    @GetMapping(value = "/orderDetail/{id}")
    public AjaxResult orderDetail(@PathVariable("id") String id) {
        TOrder tOrder = tOrderService.selectTOrderById(id);
        System.out.println(SecurityUtils.getUserIdStrSS());
        return AjaxResult.success(tOrder);
    }



    @Autowired
    private ITSubmoneyRecordService submoneyRecordService;

    public void saveUserMoneyAndSubRecord(String orderId, BigDecimal money, String type,String userId) {
        BigDecimal totalMoney = tWalletService.getTotalMoney();
        // 判断是余额是否充足
        if (totalMoney.compareTo(money) < 0) {
            throw new ServiceException("余额不足");
        }
        // 普通订单扣除余额
        TWallet tWallet = new TWallet();
        tWallet.setUserId(userId);
        tWallet.setBusinessId(orderId);
        tWallet.setMoney(money);
        tWallet.setType(type);
        if("2".equals(type)){
            tWallet.setRemark("报价扣除保证金");
        }else if("1".equals( type)){
            tWallet.setRemark("订单扣除余额");
        }else if("3".equals( type)){
            tWallet.setRemark("保证金返还");
        }else if("9".equals(type)){
            tWallet.setRemark("强制仲裁费用");
        }
        tWalletService.save(tWallet);
    }
     @Autowired
    private ITOrderNoticeService orderNoticeService;

    /**
     * 保存订单消息记录
     */
    @PostMapping("/addOrderNotice")
    @RepeatSubmit
    @Transactional
    public AjaxResult addOrderNotice(@Validated @RequestBody TOrderNotice vo) {
        String type = vo.getType();
        String orderId = vo.getOrderId();
        TOrder order = tOrderService.getById(orderId);
        String fduserId = order.getUserId();
        String playUserId = order.getPlayUserId();
        Boolean isfdr=false;
        if(fduserId.equals(SecurityUtils.getUserIdStr())){
            isfdr=true;
        }
        // 判断是否有担保人
        QueryWrapper<TOrderDbrRecord> queryWrapperDb = new QueryWrapper<>();
        queryWrapperDb.eq("order_id", orderId);
        queryWrapperDb.eq("type","1");
        List<TOrderDbrRecord> dbrlist = orderDbrRecordService.list(queryWrapperDb);
        String dbrUserId="";
        if(!CollectionUtils.isEmpty(dbrlist)){
            TOrderDbrRecord tOrderDbrRecord = dbrlist.get(0);
            // 担保人
             dbrUserId = tOrderDbrRecord.getDbrUserId();
        }
        String  noticeContent="";
        if ("2".equals(type)) {
            String orderType = order.getType();
            if(!"2".equals(orderType)){
                throw  new ServiceException("该订单不是代练订单");
            }
            // 报价信息
            // 判端是否已经出价
            QueryWrapper<TOrderNotice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", vo.getOrderId());
            queryWrapper.eq("send_user_id", SecurityUtils.getUserIdStr());
            queryWrapper.eq("type", type);
            if (orderNoticeService.count(queryWrapper) > 0) {
                return AjaxResult.error("已经出价");
            }
            TOrderNotice  orderNotice = new TOrderNotice();
            // 发送人
            orderNotice.setSendUserId(SecurityUtils.getUserIdStr());
            orderNotice.setReceiveUserId(fduserId);
            // 是否需要操作
            orderNotice.setIsNeedOper("1");
            // 操作人
            orderNotice.setOperUserId(fduserId);
            // 需要操作的类型 1 确定
            orderNotice.setOperType("1");
            orderNotice.setUserInfo(vo.getUserInfo());
            orderNotice.setPlayMoney(vo.getPlayMoney());
            noticeContent="发单人报价信息了";
            orderNotice.setContent(noticeContent);
            orderNotice.setOrderId(orderId);
            orderNotice.setType(type);
            orderNoticeService.save(orderNotice);
            BigDecimal bzPrice = order.getBzPrice();
            if(bzPrice==null){
                throw  new ServiceException("该订单没有保证金");
            }
            // 扣除代练师的余额不保存分账记录
            this.saveUserMoneyAndSubRecord(order.getId(), order.getBzPrice().negate(), "2",SecurityUtils.getUserIdStr());
        }else if("3".equals( type)){
            String orderStatus = order.getOrderStatus();
            if(!"2".equals(orderStatus)){
                throw  new ServiceException("订单状态异常");
            }
            // 打手发送完成通知，用户确认（是 否）
            TOrderNotice  orderNotice = new TOrderNotice();
            orderNotice.setOrderId(orderId);
            orderNotice.setType("3");
            // 发送人
            orderNotice.setSendUserId(SecurityUtils.getUserIdStr());
            orderNotice.setReceiveUserId(fduserId);
            // 是否需要操作
            orderNotice.setIsNeedOper("1");
            // 操作人
            orderNotice.setOperUserId(fduserId);
            // 需要操作的类型 1 确定
            orderNotice.setOperType("1");
            noticeContent="打手申请订单完成";
            orderNotice.setContent(noticeContent);
            orderNoticeService.save(orderNotice);
        }else if("4".equals( type)){
            // 提交异常 自行协商（已接单）
            // 判断 存在还未处理的意见
            QueryWrapper<TOrderNotice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderId);
            queryWrapper.eq("type", type);
            // 发单人意见和打手意见都为空
            queryWrapper.isNull("fd_yj");
            queryWrapper.isNull("play_yj");
            if (orderNoticeService.count(queryWrapper) > 0) {
                return AjaxResult.error("存在还未处理的意见");
            }
            String jdStatus =order.getJdStatus();
            if("3".equals(jdStatus) || "4".equals(jdStatus) || "5".equals(jdStatus)  || "6".equals(jdStatus)){
                return AjaxResult.error("已经申请过担保人介入");
            }
            //如果已经申请过 申请担保人接入 就不能自行协商
            QueryWrapper<TOrderNotice> queryWrapperdb = new QueryWrapper<>();
            queryWrapperdb.eq("order_id", orderId);
            queryWrapperdb.eq("type", "5");
            if (orderNoticeService.count(queryWrapper) > 0) {
                return AjaxResult.error("已经申请过担保人介入");
            }
            // 最多提两次记录
            QueryWrapper<TOrderNotice> queryWrapperCOUNT = new QueryWrapper<>();
            queryWrapperCOUNT.eq("order_id", orderId);
            queryWrapperCOUNT.eq("type", type);
            queryWrapperCOUNT.eq("send_user_id", SecurityUtils.getUserIdStr());
            if (orderNoticeService.count(queryWrapperCOUNT) > 1) {
                return AjaxResult.error("最多提两次记录");
            }

            String orderStatus = order.getOrderStatus();
            if(!"2".equals(orderStatus)  && !"4".equals(orderStatus)){
                throw  new ServiceException("订单状态异常");
            }
            if(!"4".equals(orderStatus)){
                // 修改成异常订单
                order.setOrderStatus("4");
                tOrderService.updateById(order);
            }
            if(vo.getFdMoney()==null  || vo.getPlayMoney() ==null  || StringUtils.isEmpty(vo.getSxfType())){
                throw  new ServiceException("方案参数有误");
            }
            // 进入自行协商阶段
            order.setJdStatus("2");
            tOrderService.updateById(order);
            TOrderNotice  orderNotice = new TOrderNotice();
            orderNotice.setOrderId(orderId);
            orderNotice.setType("4");
            if(isfdr){
                // 如果是发单人
                // 发送人
                orderNotice.setSendUserId(fduserId);
                orderNotice.setReceiveUserId(playUserId);
                // 操作人是打手
                orderNotice.setOperUserId(playUserId);
                orderNotice.setFdYj("1");
                orderNotice.setFdYjDate(new Date());
            }else{
                // 如果是打手
                orderNotice.setSendUserId(playUserId);
                orderNotice.setReceiveUserId(fduserId);
                // 操作人是发单人
                orderNotice.setOperUserId(fduserId);
                orderNotice.setPlayYj("1");
                orderNotice.setPayYjDate(new Date());
            }
            orderNotice.setPlayMoney(vo.getPlayMoney());
            orderNotice.setFdMoney(vo.getFdMoney());
            orderNotice.setSxfType(vo.getSxfType());
            // 是否需要操作
            orderNotice.setIsNeedOper("1");
            // 需要操作的类型 1 确定
            orderNotice.setOperType("1");
            noticeContent="自行协商方案通知";
            orderNotice.setContent(noticeContent);
            orderNoticeService.save(orderNotice);
        }else if("5".equals( type)){
            // 发送介入通知 给担保人（双方只发一次就可以了）
//            if (CollectionUtils.isEmpty(dbrlist)) {
//                return  AjaxResult.error("待担保人接单");
//            }
            // 提交异常  担保人介入（已接单）
            String orderStatus = order.getOrderStatus();
            if(!"2".equals(orderStatus)  && !"4".equals(orderStatus)){
               // throw  new ServiceException("订单状态异常");
            }
            if(!"4".equals(orderStatus)){
                // 修改成异常订单
                order.setOrderStatus("4");
                tOrderService.updateById(order);
            }
            if(StringUtils.isNotEmpty(dbrUserId)){
                // 如果有担保人
                TOrderNotice  orderNotice = new TOrderNotice();
                orderNotice.setOrderId(orderId);
                orderNotice.setType("5");
                if(isfdr){
                    // 如果是发单人
                    orderNotice.setSendUserId(fduserId);
                    orderNotice.setReceiveUserId(dbrUserId);
                }else{
                    // 如果是打手
                    orderNotice.setSendUserId(playUserId);
                    orderNotice.setReceiveUserId(dbrUserId);
                }
                orderNotice.setContent("申请担保人介入通知");
                orderNoticeService.save(orderNotice);
            }else {
                String needDbr = order.getNeedDbr();
                if(!"1".equals(needDbr)){
                    // 如果一开始选择是不需要担保人 介入
                    order.setNeedDbr("1");
                }
            }
            // 申请担保人介入
            order.setJdStatus("3");
            tOrderService.updateById(order);

        }else if("6".equals( type)){
            //  担保人出具方案,凭证。有可能到申请仲裁的时候，双方选择按担保人意见，再回来这个流程
            if(vo.getFdMoney()==null  || vo.getPlayMoney() ==null  || StringUtils.isEmpty(vo.getSxfType())  || vo.getPzFile()==null){
                return AjaxResult.error("方案参数有误");
            }

            QueryWrapper<TOrderNotice> queryWrapperCOUNT = new QueryWrapper<>();
            queryWrapperCOUNT.eq("order_id", orderId);
            queryWrapperCOUNT.eq("type", type);
            queryWrapperCOUNT.last("and ( dbr_yj is null  or play_yj is null  )");
//            if (orderNoticeService.count(queryWrapperCOUNT) > 0) {
//                return AjaxResult.error("已经提交过担保方案，等待对方处理");
//            }
            TOrderNotice  orderNotice = new TOrderNotice();
            orderNotice.setOrderId(orderId);
            orderNotice.setType("6");
            // 担保人发送
            orderNotice.setSendUserId(SecurityUtils.getUserIdStr());
            //接收人是 打手和 打单人
            orderNotice.setReceiveUserId(playUserId+","+fduserId);
            orderNotice.setContent("担保人出具方案通知");
            // 是否需要操作
            orderNotice.setIsNeedOper("1");
            // 需要操作的类型 1 确定
            orderNotice.setOperType("1");
            // 操作人
            orderNotice.setOperUserId(playUserId+","+fduserId);
            orderNotice.setPzFile(vo.getPzFile());
            orderNotice.setPlayMoney(vo.getPlayMoney());
            orderNotice.setFdMoney(vo.getFdMoney());
            orderNotice.setSxfType(vo.getSxfType());
            orderNoticeService.save(orderNotice);
            // 担保人介入
            order.setJdStatus("4");
            tOrderService.updateById(order);
        }else if("7".equals(type)){
            // 拒绝担保人方案通知

        }else if("8".equals( type)){
            // 申请仲裁  由 担保人发起,打手和发单人
            TOrderNotice  orderNotice = new TOrderNotice();
            orderNotice.setOrderId(orderId);
            orderNotice.setType("8");
            // 担保人发送
            orderNotice.setSendUserId(SecurityUtils.getUserIdStr());
            //接收人是 打手和 打单人
            orderNotice.setReceiveUserId(playUserId+","+fduserId);
            orderNotice.setContent("担保人申请仲裁，请选择仲裁费承担方式");
            // 是否需要操作
            orderNotice.setIsNeedOper("1");
            // 需要操作的类型 1 确定
            orderNotice.setOperType("1");
            // 操作人
            orderNotice.setOperUserId(playUserId+","+fduserId);
            orderNoticeService.save(orderNotice);
//            tOrderService.updateById(order);
        }else if("10".equals( type)){
            // 原始担保人给出方案，另外两个人需要同意一致
            // 判断是否有担保人
            QueryWrapper<TOrderDbrRecord> queryWrapperDbtotal = new QueryWrapper<>();
            queryWrapperDbtotal.eq("order_id", orderId);
            queryWrapperDbtotal.eq("type", "2");
            List<TOrderDbrRecord> dbrlisttotal = orderDbrRecordService.list(queryWrapperDbtotal);
            if(dbrlisttotal.size()<2){
                return AjaxResult.error("请选择其他担保人");
            }
            QueryWrapper<TOrderNotice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderId);
            queryWrapper.eq("type", "10");
            queryWrapper.last("and ( dbr_yj1 is null  or dbr_yj2 is null  )");
            //第一个担保人意见为空 或 第二个担保人意见为空
            List<TOrderNotice> list = orderNoticeService.list(queryWrapper);
            if(!CollectionUtils.isEmpty(list)){
                return AjaxResult.error("请等待其他担保人处理");
            }
            //  担保人出具方案,凭证
            if(vo.getFdMoney()==null  || vo.getPlayMoney() ==null  || StringUtils.isEmpty(vo.getSxfType())  || vo.getPzFile()==null){
                return AjaxResult.error("方案参数有误");
            }
            // 如果仲裁费用的支付方式是败方支付，则 需要传 败方
            String jdStatus = order.getJdStatus();
            String zcType = order.getZcType();
            String failureType = vo.getFailureType();
            if("5".equals(jdStatus)){
                if("1".equals(zcType)  &&  StringUtils.isEmpty(failureType)){
                    return AjaxResult.error("请选择失败方");
                }
            }
            // 申请仲裁  由 担保人发起,打手和发单人
            TOrderNotice  orderNotice = new TOrderNotice();
            orderNotice.setOrderId(orderId);
            orderNotice.setType("10");
            // 担保人发送
            orderNotice.setSendUserId(SecurityUtils.getUserIdStr());
            String collect = dbrlisttotal.stream().map(TOrderDbrRecord::getDbrUserId).collect(Collectors.joining(","));
            //接收人是 另外两个担保人
            orderNotice.setReceiveUserId(collect);
            orderNotice.setContent("仲裁方案请确认");
            // 是否需要操作
            orderNotice.setIsNeedOper("1");
            // 需要操作的类型 1 确定
            orderNotice.setOperType("1");
            orderNotice.setPlayMoney(vo.getPlayMoney());
            orderNotice.setFdMoney(vo.getFdMoney());
            orderNotice.setSxfType(vo.getSxfType());
            orderNotice.setFailureType(failureType);
            //  dbrlisttotal 遍历 担保人id 逗号隔开
            // 操作人
            orderNotice.setOperUserId(collect);
            orderNoticeService.save(orderNotice);
        }
        return AjaxResult.success();
    }
    /**
    * 操作消息
    */
    @PostMapping("/operOrderNotie")
    @RepeatSubmit
    @Transactional
    public AjaxResult operOrderNotie(@RequestBody TOrderNotice vo){
        String id = vo.getId();
        if(StringUtils.isEmpty( id)){
            return AjaxResult.error("参数错误");
        }
        TOrderNotice orderNotice = orderNoticeService.getById(id);
        String type = orderNotice.getType();
        String orderId = orderNotice.getOrderId();
        TOrder order = tOrderService.getById(orderId);
        String fduserId = order.getUserId();
        String playUserId = order.getPlayUserId();
        BigDecimal bzPrice = order.getBzPrice();
        String fdYj = vo.getFdYj();
        String dbrYj = vo.getDbrYj();
        String playYj = vo.getPlayYj();
        // 担保人意见
        String playYj_old= orderNotice.getPlayYj();
        String fdYj_old = orderNotice.getFdYj();
        // 判断是否有担保人
        QueryWrapper<TOrderDbrRecord> queryWrapperDb = new QueryWrapper<>();
        queryWrapperDb.eq("order_id", orderId);
        queryWrapperDb.eq("type","1");
        List<TOrderDbrRecord> dbrlist = orderDbrRecordService.list(queryWrapperDb);
        String dbrUserId="";
        if(!CollectionUtils.isEmpty(dbrlist)){
            TOrderDbrRecord tOrderDbrRecord = dbrlist.get(0);
            // 担保人
            dbrUserId = tOrderDbrRecord.getDbrUserId();
        }

        Boolean isfdr=false;
        if(fduserId.equals(SecurityUtils.getUserIdStr())){
            isfdr=true;
        }
        if ("2".equals(type)) {
            // 出价操作
           if(!"1".equals(order.getOrderStatus())){
               throw  new ServiceException("订单状态异常");
           }
            // 处理完成通知
            if(StringUtils.isAnyBlank(fdYj)){
                return AjaxResult.error("请填写意见");
            }
            if("1".equals(fdYj)){
                // 发单人同意 改成已接单
                order.setOrderStatus("2");
                order.setPlayUserId(orderNotice.getSendUserId());
                order.setOrderPrice(orderNotice.getPlayMoney());
                // （1）扣除用户的余额
                this.saveUserMoneyAndSubRecord(order.getId(), order.getOrderPrice().negate(), "1",fduserId);
                tOrderService.updateById(order);
                //(3) 如果有其他打手报价 ，将没有选中的保证金退回
                QueryWrapper<TOrderNotice> bzjth = new QueryWrapper<>();
                bzjth.eq("order_id", orderId);
                bzjth.eq("type","2");
                bzjth.ne("send_user_id",orderNotice.getSendUserId());
                List<TOrderNotice> listdh = orderNoticeService.list(bzjth);
                if(!CollectionUtils.isEmpty(listdh)){
                    for (TOrderNotice notice : listdh) {
                        // 退回保证金
                        this.saveUserMoneyAndSubRecord(order.getId(), order.getBzPrice().negate(), "3",notice.getSendUserId());
                    }
                }
                // 异步创建群聊
                CompletableFuture.runAsync(() -> {
                    // 创建群聊
                    String hxGroupId = this.createOrderGroup(order);
                    // 添加一个成员打手
                    this.addMemberToGroup(hxGroupId, order.getPlayUserId());
                    //  添加一个成员担保人
                    this.addMemberToGroupDbr(hxGroupId, order.getId());
                });
            }
            orderNotice.setFdYj(fdYj);
            orderNotice.setFdYjDate(new Date());
            orderNoticeService.updateById(orderNotice);
        }else if("3".equals(type)){
            // 处理完成通知
            if(StringUtils.isAnyBlank(fdYj)){
                return AjaxResult.error("请填写意见");
            }
            if(!"2".equals(order.getOrderStatus())){
                throw  new ServiceException("订单状态异常");
            }
            if("1".equals(fdYj)) {
                // 发单人同意完成,完成订单
                this.finishOrder(order, orderNotice,"");
            }
            orderNotice.setFdYj(fdYj);
            orderNotice.setFdYjDate(new Date());
            orderNoticeService.updateById(orderNotice);
        }else if("4".equals( type)){
            //提交异常--自行协商（双方都可以发送）
            if(StringUtils.isEmpty(fdYj)  && StringUtils.isEmpty(playYj)){
                return AjaxResult.error("请填写意见");
            }
            if(!"4".equals(order.getOrderStatus())){
                throw  new ServiceException("订单状态异常");
            }
            if(StringUtils.isNotEmpty(fdYj)){
                orderNotice.setFdYj(fdYj);
                orderNotice.setFdYjDate(new Date());
            }else{
                orderNotice.setPlayYj(playYj);
                orderNotice.setPayYjDate(new Date());
            }

            orderNoticeService.updateById(orderNotice);
            TOrderNotice orderNoticenow = orderNoticeService.getById(id);
            String fdYj_now= orderNoticenow.getFdYj();
            String playYj_now = orderNoticenow.getPlayYj();
            // 处理自行自行协商方案
            // 如果是发单人同意了 并且打手也同意了
            if("1".equals(fdYj_now) && "1".equals(playYj_now)){
                    // 订单完成
                    this.finishOrder(order,orderNotice,"异常订单金额自行协商方分配达成一致");
            }
            if("2".equals(fdYj_now)  || "2".equals(playYj_now)){
                order.setJdStatus("2-1");
                tOrderService.updateById(order);
            }
            //
        }else if("5".equals(type)){
            // 申请担保人介入不需要 担保人处理
        }else if("6".equals( type)){
            // 担保人出具了方案（打手和 发单人处理）
            if(StringUtils.isEmpty(fdYj)  &&  StringUtils.isEmpty(playYj) ){
                return AjaxResult.error("请填写意见");
            }
            if(StringUtils.isNotEmpty(fdYj)){
                orderNotice.setFdYj(fdYj);
                orderNotice.setFdYjDate(new Date());
            }else{
                orderNotice.setPlayYj(playYj);
                orderNotice.setPayYjDate(new Date());
            }
            orderNoticeService.updateById(orderNotice);
            TOrderNotice ordernoticeNow = orderNoticeService.getById(id);
             String fdYj_now= ordernoticeNow.getFdYj();
            String playYj_now = ordernoticeNow.getPlayYj();
            // 如果是发单人同意了 并且打手也同意了
            if("1".equals(fdYj_now) && "1".equals(playYj_now)){
                // 订单完成
                this.finishOrder(order,orderNotice,"异常订单金额分配担保人方案分配达成一致");
            }else{
                if("2".equals(fdYj)  ||   "2".equals(playYj)){
                    // 有一方不同意 发送拒绝通知给担保人
                    TOrderNotice  orderNoticeagree = new TOrderNotice();
                    orderNoticeagree.setOrderId(orderId);
                    orderNoticeagree.setType("7");
                    //  打手和 打单人 发送
                    orderNoticeagree.setSendUserId(SecurityUtils.getUserIdStr());
                    //接收人是 担保人
                    orderNoticeagree.setReceiveUserId(dbrUserId);
                    if("2".equals(fdYj)){
                        orderNoticeagree.setContent("发单人拒绝了担保人出具方案通知");
                    }else {
                        orderNoticeagree.setContent("打手拒绝了担保者出具方案通知");
                    }
                    orderNoticeService.save(orderNoticeagree);
                    // 一方拒绝
                    order.setJdStatus("4-1");
                    tOrderService.updateById(order);
                }
            }
        }else if("8".equals( type)){
            // 双方处理担保人提出的仲裁申请 ，填写选择仲裁费用支付方式
            // 有任意一方选择按担保意见 ，拒绝进入仲裁阶段
            String playZcType = vo.getPlayZcType();
            String fdZcType = vo.getFdZcType();
            if(StringUtils.isEmpty(playZcType)  &&  StringUtils.isEmpty(fdZcType) ){
                return AjaxResult.error("请填写仲裁费用支付方式");
            }
            if(StringUtils.isNotEmpty(playZcType)){
                orderNotice.setPlayZcType(playZcType);
                orderNotice.setPayYjDate(new Date());
            }else if(StringUtils.isNotEmpty(fdZcType)){
                orderNotice.setFdZcType(fdZcType);
                orderNotice.setFdYjDate(new Date());
            }
            orderNoticeService.updateById(orderNotice);
            TOrderNotice noticeNow = orderNoticeService.getById(id);
            String playZcType_now= noticeNow.getPlayZcType();
            String fdZcType_now= noticeNow.getFdZcType();
            if("3".equals(playZcType_now)   || "3".equals(fdZcType_now)){
                // 一方选择了 按担保人意见
                TOrderNotice  orderNoticeagree = new TOrderNotice();
                orderNoticeagree.setOrderId(orderId);
                orderNoticeagree.setType("8-1");
                orderNoticeagree.setSendUserId(SecurityUtils.getUserIdStr());
                orderNoticeagree.setReceiveUserId(dbrUserId);
                orderNoticeagree.setContent("发单人/接单人选择了按担保意见结算，请担保人给出意见");
                orderNoticeService.save(orderNoticeagree);
            }
            if(!StringUtils.isAnyBlank(playZcType_now,fdZcType_now)){
                //1 败方支付 2 双方 AA 3 按担保意见  优先级  败方支付大于双方AA大
                if(!"3".equals(playZcType_now) && ! "3".equals(fdZcType_now)){
                    // 进入仲裁阶段
                    String zcType="";
                    if("1".equals(playZcType_now)|| "1".equals(fdZcType_now) ){
                        // 有一方选择了 败方支付,按照失败方
                        zcType="1";
                    }else{
                        zcType="2";
                    }
                    // 更新仲裁费用支付方式
                    vo.setZcType(zcType);
                    orderNoticeService.updateById(vo);
                    // 进入仲裁
                    order.setJdStatus("5");
                    // 总裁费用支付方式
                    order.setZcType(zcType);
                    tOrderService.updateById(order);
                    // 发送进入仲裁通知
                    TOrderNotice  orderNoticeagree = new TOrderNotice();
                    orderNoticeagree.setOrderId(orderId);
                    orderNoticeagree.setType("9");
                    orderNoticeagree.setSendUserId(SecurityUtils.getUserIdStr());
                    orderNoticeagree.setReceiveUserId(playUserId+","+fduserId);
                    orderNoticeagree.setContent("订单进入仲裁阶段");
                    orderNoticeService.save(orderNoticeagree);
                }

            }
        }else if("10".equals( type)){
            //  原始担保人给出方案，另外两个担保人需要同意一致，结束订单
            String dbrYj1 = vo.getDbrYj1();
            String dbrYj2 = vo.getDbrYj2();
            if(StringUtils.isEmpty(dbrYj1)  && StringUtils.isEmpty(dbrYj2)){
                return AjaxResult.error("请填写意见");
            }
            if(StringUtils.isNotEmpty(dbrYj1)){
                orderNotice.setDbrYj1(dbrYj1);
                orderNotice.setDbrYj1Date(new Date());
            }else if(StringUtils.isNotEmpty(dbrYj2)){
                orderNotice.setDbrYj2(dbrYj2);
                orderNotice.setDbrYj2Date(new Date());
            }
            orderNoticeService.updateById(orderNotice);
            TOrderNotice noticeNow = orderNoticeService.getById(id);
            String dbrYj1_now = noticeNow.getDbrYj1();
            String dbrYj2_now = noticeNow.getDbrYj2();
            if(!StringUtils.isEmpty(dbrYj1_now)  && !StringUtils.isEmpty(dbrYj2_now)   ){
                // 检查是否两个担保人都同意
                if ("1".equals(dbrYj1_now) && "1".equals(dbrYj2_now)) {
                    // 如果两个担保人都同意，则按照担保人的方案完成订单
                    this.finishOrder(order, orderNotice, "仲裁订单金额分配担保人方案分配达成一致");
                    return AjaxResult.success("订单已完成");
                } else {
                    return AjaxResult.success("已记录不同意见，等待进一步处理");
                }
            }

        }

        return  AjaxResult.success();
   }

    /**
     * 下架
     */
   @PostMapping("xjOrder")
   public AjaxResult xjOrder(@RequestBody  TOrder tOrder) {
       String id = tOrder.getId();
       TOrder byId = tOrderService.getById(id);
       if(byId==null){
           return AjaxResult.error("订单不存在");
       }
       if(!"1".equals(byId.getOrderStatus())){
           return AjaxResult.error("订单状态不正确");
       }
       byId.setStatus("2");
       byId.setOrderStatus("9");
       tOrderService.updateById(byId);
       return AjaxResult.success();
   }


    public void finishOrder(TOrder tOrder,TOrderNotice orderNotice,String reason) {
        // 已完成
        tOrder.setOrderStatus("3");
        tOrder.setFinallyTime(DateUtils.getNowDate());
        tOrderService.updateById(tOrder);
        // 平台抽成百分比
        String ptccbl = configService.getConfigValue("ptccbl");
        //担保人抽成比例
        String dbrccbl = configService.getConfigValue("dbrccbl");
        // 判断是否有担保人
        QueryWrapper<TOrderDbrRecord> queryWrapperDb = new QueryWrapper<>();
        queryWrapperDb.eq("order_id", tOrder.getId());
        queryWrapperDb.eq("type","1");
        List<TOrderDbrRecord> dbrlist = orderDbrRecordService.list(queryWrapperDb);
        String dbrUserId="";
        if(!CollectionUtils.isEmpty(dbrlist)){
            TOrderDbrRecord tOrderDbrRecord = dbrlist.get(0);
            // 担保人
            dbrUserId = tOrderDbrRecord.getDbrUserId();
        }
        // 打手分账
        BigDecimal playSubMoney = BigDecimal.ZERO;
        // 发单人分账
        BigDecimal fdSubMoney =  BigDecimal.ZERO;
        // 订单总金额
        BigDecimal totalMoney = tOrder.getOrderPrice().add(tOrder.getBzPrice());
        //平台抽成
        BigDecimal ptCcMoney =NumberUtil.mul(totalMoney,new BigDecimal(ptccbl));
        // 担保人抽成
        BigDecimal dbrCcMoney  = BigDecimal.ZERO;
        if(StringUtils.isNotEmpty(dbrUserId)){
            // 担保人抽成
            dbrCcMoney = totalMoney.multiply(new BigDecimal(dbrccbl));
        }
        //1 双方平摊 2 按最终比例分配 3 发单人支付   4   代练师支付
        String sxfType = orderNotice.getSxfType();
        String type = orderNotice.getType();
        // 总抽成
        BigDecimal  totalccMoney=ptCcMoney.add(dbrCcMoney);
        if("3".equals( type)){
            // 打手承担服务费(平台抽成  和 担保人抽成)
            playSubMoney = NumberUtil.sub(totalMoney,ptCcMoney,dbrCcMoney);
        }
        if("4".equals(type)  ||  "6".equals(type)  || "10".equals(type)){
            fdSubMoney = orderNotice.getFdMoney();
            playSubMoney = orderNotice.getPlayMoney();
            if("1".equals(sxfType)){
                // 双方平摊
                // 打手的分账金额
                BigDecimal divhalf = NumberUtil.div(totalMoney, 2);
                fdSubMoney=fdSubMoney.subtract(divhalf);
                playSubMoney=playSubMoney.subtract(divhalf);
            }else if("2".equals(sxfType)){
                // 按照 最终比例分配，计算手续费的金额
                BigDecimal  playsxf =  totalccMoney.multiply(NumberUtil.div(playSubMoney,totalMoney));
                // 发单人的手续费
                BigDecimal fdsxf =  totalccMoney.subtract(playsxf);
                fdSubMoney=fdSubMoney.subtract(fdsxf);
                 playSubMoney=playSubMoney.subtract(playsxf);
            }else if("3".equals(sxfType)){
                //发单人支付
                fdSubMoney=fdSubMoney.subtract(totalccMoney);
            }else if("4".equals(sxfType)){
                //代练师支付
                playSubMoney=playSubMoney.subtract(totalccMoney);
            }
        }
        if(playSubMoney.compareTo(BigDecimal.ZERO) != 0){
            TWallet  wallet =new TWallet();
            wallet.setUserId(tOrder.getPlayUserId());
            wallet.setMoney(playSubMoney);
            wallet.setType("4");
            wallet.setRemark("订单结束给打手分账");
            tWalletService.save(wallet);
        }
        if(fdSubMoney.compareTo(BigDecimal.ZERO) != 0){
            TWallet  wallet =new TWallet();
            wallet.setUserId(tOrder.getPlayUserId());
            wallet.setMoney(fdSubMoney);
            wallet.setType("4");
            wallet.setRemark("订单结束给发单人分账");
            tWalletService.save(wallet);
        }
        if(dbrCcMoney.compareTo(BigDecimal.ZERO)!= 0){
            TWallet  wallet1 =new TWallet();
            wallet1.setUserId(dbrUserId);
            wallet1.setMoney(dbrCcMoney);
            wallet1.setType("6");
            wallet1.setRemark("订单结束给担保人分账");
            tWalletService.save(wallet1);
        }
        if(ptCcMoney.compareTo(BigDecimal.ZERO)!= 0){
            TWallet  wallet2 =new TWallet();
            wallet2.setUserId("1");
            wallet2.setMoney(ptCcMoney);
            wallet2.setType("5");
            wallet2.setRemark("订单结束给平台分账");
            tWalletService.save(wallet2);
        }
        //
        // 这里还涉及到一个仲裁费用  todo


    }

    /**
     *  订单查询消息记录
     */
    @GetMapping("/orderNoticeList")
    public    AjaxResult orderNoticeList(TOrderNotice orderNotice) {
        List<TOrderNotice> list = orderNoticeService.selectTOrderNoticeList(orderNotice);
        return AjaxResult.success(list);
    }

    /**
     *  订单查询--我的消息记录
     */
    @GetMapping("/myOrderNoticeList")
    public    TableDataInfo myOrderNoticeList(TOrderNotice orderNotice) {
        orderNotice.setReceiveUserId(SecurityUtils.getUserIdStr());
        List<TOrderNotice> list = orderNoticeService.selectTOrderNoticeList(orderNotice);
        return getDataTable( list);
    }

    @Autowired
    private ITNoticeService tNoticeService;

    /**
     *  系统消息我的消息(分页)
     */
    @GetMapping("/getXtlist")
    public   TableDataInfo getXtlist(TNotice tNotice) {
        startPage();
        tNotice.setReceiveUserId(SecurityUtils.getUserIdStr());
        List<TNotice> list = tNoticeService.selectTNoticeList(tNotice);
        return getDataTable(list);
    }



    /**
     *  强制仲裁
     */
    @PostMapping("/sqQzZcOrder")
    @Transactional
    public AjaxResult sqQzZcOrder(@RequestBody TOrder tOrder) {
        TOrder oldOrder = tOrderService.getById(tOrder.getId());
        String orderStatus = oldOrder.getOrderStatus();
        String jdStatus = oldOrder.getJdStatus();
        // 必须是异常订单
        if(!"4".equals(orderStatus)){
            return AjaxResult.error("订单状态错误");
        }
        if("5".equals(jdStatus)  || "6".equals(jdStatus)){
            return AjaxResult.error("已经进入仲裁");
        }
        // 强制仲裁
        oldOrder.setJdStatus("6");
        tOrderService.updateById(oldOrder);
        String zcFee = configService.getConfigValue("zc_fee");
        if(StringUtils.isEmpty(zcFee)){
            throw  new ServiceException("请配置仲裁费用");
        }
        // 扣除仲裁费用
        this.saveUserMoneyAndSubRecord(oldOrder.getId(), new BigDecimal(zcFee).negate(), "9",SecurityUtils.getUserIdStr());
        return  AjaxResult.success();
    }





    /**
     * 普通订单抢单（待接单----->已接单）传订单Id
     */
    @PostMapping("/grabOrder")
    public AjaxResult grabOrder(@RequestBody TOrder tOrder) {
        TOrder oldOrder = tOrderService.getById(tOrder.getId());
        String type = oldOrder.getType();
        String orderStatus = oldOrder.getOrderStatus();
        if(!"1".equals(orderStatus) || !"1".equals(type)){
            return AjaxResult.error("订单状态错误");
        }
        oldOrder.setPlayUserId(SecurityUtils.getUserIdStr());
        oldOrder.setOrderStatus("2");
        tOrderService.updateById(oldOrder);
        // 扣除代练师的余额并保存分账记录
        this.saveUserMoneyAndSubRecord(oldOrder.getId(), oldOrder.getBzPrice().negate(), "2",SecurityUtils.getUserIdStr());
        // 异步创建群聊
        CompletableFuture.runAsync(() -> {
            // 创建群聊
            String hxGroupId = this.createOrderGroup(oldOrder);
            // 添加一个成员 打手
            this.addMemberToGroup(hxGroupId, oldOrder.getPlayUserId());
            // 添加一个成员 担保人
            this.addMemberToGroupDbr(hxGroupId, oldOrder.getId());

        });
        return  AjaxResult.success();
    }


    public   void  addMemberToGroupDbr(String hxGroupId, String order_id){
        QueryWrapper<TOrderDbrRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", order_id);
        List<TOrderDbrRecord> dbrRecordlist = orderDbrRecordService.list(queryWrapper);
        for (int i = 0; i < dbrRecordlist.size(); i++) {
            TOrderDbrRecord tOrderDbrRecord = dbrRecordlist.get(i);
            // 担保人Id
            String dbrUserId = tOrderDbrRecord.getDbrUserId();
            QueryWrapper<GroupMember> querymemberWrapper = new QueryWrapper<>();
            querymemberWrapper.eq("group_id", hxGroupId);
            querymemberWrapper.eq("user_id", dbrUserId);
            long count = groupMemberService.count(querymemberWrapper);
            if(count==0){
                this.addMemberToGroup(hxGroupId, dbrUserId);
            }
        }
    }


    public   String  createOrderGroup(TOrder oldOrder){
        TGroup group = new TGroup();
        group.setGroupName(oldOrder.getTitle());
        String hxGroupId = hxSevice.createGroup(group.getGroupName(), group.getDescription(), oldOrder.getUserId());
        if(StringUtils.isEmpty(hxGroupId)){
            throw  new RuntimeException("创建群聊失败");
        }
        group.setGroupId(hxGroupId);
        group.setOrderId(oldOrder.getId());
        group.setOwnerId(oldOrder.getUserId());
        tGroupService.save(group);
        // 添加环信一个成员
        this.addMemberToGroup(hxGroupId, oldOrder.getUserId());
        // 添加一个成员
        GroupMember groupMember = new GroupMember();
        groupMember.setGroupId(hxGroupId);
        groupMember.setRole("2");
        groupMember.setUserId(oldOrder.getUserId());
        groupMemberService.save(groupMember);
        return hxGroupId;
    }

    /**
     * 根据用户id数组 ，查询用户对象集合
     */
    @GetMapping("/getUserByIds")
    public AjaxResult getUserByIds(@RequestParam List<Long> userIds) {
        SysUser sysUser = new  SysUser();
        List<SysUser> users = sysUserService.selectUserListApp(sysUser);
        return AjaxResult.success(users);
    }

    /**
     * 担保人抢单成为原始担保人
     */
    @PostMapping("/dbrGrabOrder")
    public AjaxResult dbrGrabOrder(@RequestBody TOrder tOrder) {
        TOrder oldOrder = tOrderService.getById(tOrder.getId());
        String playUser = oldOrder.getPlayUserId();
        if(StringUtils.isEmpty(playUser)){
            return AjaxResult.error("该订单没有代练师无法抢单");
        }
        QueryWrapper<TOrderDbrRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",tOrder.getId());
        queryWrapper.eq("dbr_user_id",SecurityUtils.getUserIdStr());
        long count = orderDbrRecordService.count(queryWrapper);
        if(count>0){
            return AjaxResult.error("您已经是担保人");
        }
        TOrderDbrRecord orderDbrRecord = new TOrderDbrRecord();
        orderDbrRecord.setOrderId(tOrder.getId());
        orderDbrRecord.setDbrUserId(SecurityUtils.getUserIdStr());
        orderDbrRecord.setSource("2");
        // 原始担保人
        orderDbrRecord.setType("1");
        orderDbrRecordService.save(orderDbrRecord);
        return  AjaxResult.success();
    }

    /**
     * 添加另外两位担保人
     */
    @PostMapping("/adddbrGrabOrder")
    public AjaxResult adddbrGrabOrder(@RequestBody TOrder vo) {
        TOrder oldOrder = tOrderService.getById(vo.getId());
        String playUser = oldOrder.getPlayUserId();
        if(StringUtils.isEmpty(playUser)){
            return AjaxResult.error("该订单没有代练师无法添加");
        }
        QueryWrapper<TOrderDbrRecord> queryWrappertotal = new QueryWrapper<>();
        queryWrappertotal.eq("order_id",vo.getId());
        long total = orderDbrRecordService.count(queryWrappertotal);
        if(total==0){
            return AjaxResult.error("该订单还没有担保人，不能加入");
        }
        if(total>=3){
            return AjaxResult.error("该订单已经添加了两位担保人");
        }
        QueryWrapper<TOrderDbrRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",vo.getId());
        queryWrapper.eq("dbr_user_id",vo.getDbrUserId());
        long count = orderDbrRecordService.count(queryWrapper);
        if(count>0){
            return AjaxResult.error("您已经是担保人");
        }
        TOrderDbrRecord orderDbrRecord = new TOrderDbrRecord();
        orderDbrRecord.setOrderId(vo.getId());
        orderDbrRecord.setDbrUserId(SecurityUtils.getUserIdStr());
        orderDbrRecord.setSource("3");
        // 原始担保人
        orderDbrRecord.setType("2");
        orderDbrRecordService.save(orderDbrRecord);
        return  AjaxResult.success();
    }



    /**
     * 发送验证码
     */
    @RepeatSubmit
    @PostMapping(value = "/nologin/sendPhoneCode")
    @Anonymous
    public AjaxResult sendPhoneCode(@RequestParam(name = "phone", required = true) String phone) {
        Boolean aBoolean = yzCodeUtils.sendPhoneCode(phone);
        if (aBoolean) {
            return AjaxResult.success("发送成功");
        } else {
            return AjaxResult.error("发送失败");
        }
    }

    @Autowired
    private ITCouponUserService couponUserService;

    /**
     * 查询用户优惠券列表
     */
    @GetMapping("/couponUserList")
    public TableDataInfo couponUserList(TCouponUser tCouponUser) {
        startPage();
        tCouponUser.setUserId(SecurityUtils.getUserIdStr());
        List<TCouponUser> list = couponUserService.selectTCouponUserList(tCouponUser);
        return getDataTable( list);
    }


    /**
     * 提现申请
     */
    @PostMapping("addtTxSq")
    public AjaxResult addtTxSq(@RequestBody TTxSq tTxSq) {
        // 判断是否有待处理的申请
        QueryWrapper<TTxSq> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("check_status", "1");
        queryWrapper.eq("user_id", getUserId());
        if (txSqService.count(queryWrapper) > 0) {
            return AjaxResult.error("有待处理的申请");
        }
        // 手续费比例
        String txsxfBl = configService.getConfigValue("txsxf_bl");
        if (txsxfBl != null) {
            // 设置手续费比例
            tTxSq.setSxfBl(new java.math.BigDecimal(txsxfBl));
            // 计算实际到账金额 = 提现金额 - 手续费
            BigDecimal txMoney = tTxSq.getTxMoney();
            BigDecimal sxf = txMoney.multiply(new java.math.BigDecimal(txsxfBl));
            tTxSq.setMoney(txMoney.subtract(sxf));
        }

        // 判断余额是否充足
        BigDecimal totalMoney = tWalletService.getTotalMoney();
        if (totalMoney.compareTo(tTxSq.getJzbMoney()) < 0) {
            return AjaxResult.error("余额不足");
        }

        tTxSq.setCheckStatus("1"); // 设置审核状态为待审核
        txSqService.save(tTxSq);
        return AjaxResult.success();
    }



    /**
     * 用户个人详细信息
     */
    @GetMapping("/getMyIfnfo")
    public AjaxResult getMyIfnfo() {
        Long userId = SecurityUtils.getUserId();
        System.out.println("用户Id::" + userId);
        SysUser sysUser = sysUserService.selectUserById(userId);
        return AjaxResult.success(sysUser);
    }


    /**
     * 用户个人详细 通过用户Id
     */
    @GetMapping("/getMyIfnfoByUserId")
    public AjaxResult getMyIfnfoByUserId(String userId) {
        SysUser sysUser = sysUserService.selectUserById(Long.valueOf(userId));
        return AjaxResult.success(sysUser);
    }

    /**
     * 修改用户信息
     */
    @PostMapping("/updateUser")
    public AjaxResult updateUser(@RequestBody SysUser dto) {
        sysUserService.updateUserApp(dto);
        return AjaxResult.success();
    }


/**
 * 绑定手机号 校验短信码
 */
@Anonymous
@PostMapping("/updatePhoneUser")
public AjaxResult updatePhoneUser(@RequestBody SysUserPhone dto) throws Exception {
    String wechatCode = dto.getWechatCode();
    String type = dto.getType();
    if(StringUtils.isEmpty(wechatCode)){
        return AjaxResult.error("微信授权码不能为空");
    }
    if(StringUtils.isEmpty( type)){
        return AjaxResult.error("请选择绑定方式");
    }
    Map<String, String> wxOpenId =new HashMap<>();
    if("1".equals( type)){
        wxOpenId = WxUtils.getWxOpenId(wechatCode);
    }else{
        wxOpenId = WxUtils.getWxAppOpenId(wechatCode);
    }
    String openId = wxOpenId.get("openId");
    if (StringUtils.isEmpty(openId)) {
        return AjaxResult.error("微信授权失败openId");
    }
    String unionId = wxOpenId.get("unionId");
    if (StringUtils.isEmpty(unionId)) {
        return AjaxResult.error("微信授权失败unionId");
    }
    // 参数校验
    if (StringUtils.isEmpty(dto.getPhonenumber()) || StringUtils.isEmpty(dto.getCode())) {
        return AjaxResult.error("手机号和验证码不能为空");
    }
    // 验证短信验证码
//    String s = yzCodeUtils.checkRedisKey(dto.getPhonenumber(), dto.getCode());
//    if (!StringUtils.isEmpty(s)) {
//        return AjaxResult.error(s);
//    }
    // 检查手机号是否已被其他用户绑定
    SysUser existingUser = sysUserService.selectUserByPhonenumber(dto.getPhonenumber());
    if(existingUser==null){
        return AjaxResult.error("该手机号未注册", "1");

    }
    String unionId1 = existingUser.getUnionId();
    if(StringUtils.isNotEmpty(unionId1)){
        return AjaxResult.error("该手机号已绑定", "2");
    }
    if("1".equals( type)){
        existingUser.setOpenId(openId);
    }else{
        existingUser.setAppOpenId(openId);
    }
    existingUser.setUnionId(unionId);
    sysUserService.updateUserApp(existingUser);
    return AjaxResult.success("手机号绑定成功");
}



    /**
     * 获取君子币余额
     */
    @GetMapping("/getUserMoney")
    public AjaxResult getUserMoney() {
        BigDecimal totalMoney = tWalletService.getTotalMoney();
        return AjaxResult.success(totalMoney);
    }

    @Autowired
    private ITGroupService tGroupService;

    @Autowired
    private IGroupMessageService groupMessageService;


    /**
     * 获取我参与的群聊
     */
    @GetMapping("/getGroupList")
    public  AjaxResult getGroupList(TGroup tGroup) {
        // 查询用户参与的所有群聊
        tGroup.setCjUserId(SecurityUtils.getUserIdStr());
        List<TGroup> groupList = tGroupService.selectTGroupList(tGroup);
        for (TGroup group : groupList) {
            // 查询该群聊的最新消息
            GroupMessage lastGroupMessage = groupMessageService.getLastGroupMessage(group.getId());
            group.setLastMessage(lastGroupMessage);
        }
        return AjaxResult.success(groupList);
    }

    @Autowired
    private  HxSevice  hxSevice;



    /**
     *
     * 创建群聊
     */
    @PostMapping("/addGroup")
    public  void  addGroup(TGroup group){
        String userIdStr = SecurityUtils.getUserIdStr();
        String hxGroupId = hxSevice.createGroup(group.getGroupName(), group.getDescription(), userIdStr);
        if(StringUtils.isEmpty(hxGroupId)){
            throw  new RuntimeException("创建群聊失败");
        }
        group.setGroupId(hxGroupId);
        group.setOwnerId(SecurityUtils.getUserIdStr());
        tGroupService.save(group);
        // 添加一个成员
        GroupMember groupMember = new GroupMember();
        groupMember.setGroupId(hxGroupId);
        groupMember.setRole("2");
        groupMember.setUserId(SecurityUtils.getUserIdStr());
        groupMemberService.save(groupMember);
    }


    /**
     * 获取群聊基本信息
     */
    @GetMapping(value = "/getGroupInfo/{groupId}")
    public AjaxResult getGroupInfo(@PathVariable("groupId") String groupId) {
        String qltx = configService.getConfigValue("qltx");
        TGroup group = tGroupService.selectTGroupByGroupId(groupId);
        if(group==null){
            return  AjaxResult.error("群聊不存在");
        }
        group.setGroupImage(qltx);
        GroupMember groupMember = new GroupMember();
        groupMember.setGroupId(group.getGroupId());
        List<GroupMember> groupMembers = groupMemberService.selectGroupMemberList(groupMember);
        group.setGroupMemberList(groupMembers);
        if(StringUtils.isNotEmpty(SecurityUtils.getUserIdStrSS())){
            // 当前用户是否在群里
            QueryWrapper<GroupMember>  groupMemberQueryWrapper = new QueryWrapper<>();
            groupMemberQueryWrapper.eq("user_id",SecurityUtils.getUserIdStr());
            groupMemberQueryWrapper.eq("group_id",groupId);
            long count = groupMemberService.count(groupMemberQueryWrapper);
            group.setIsMember(count>0);
        }else{
            group.setIsMember(false);
        }

        return AjaxResult.success(group);
    }


    /**
     * 获取当前用户的客服
     */
    @GetMapping(value = "/getKf")
    public AjaxResult getKf(){
        SysUser sysUser = sysUserService.selectUserById(SecurityUtils.getUserId());
        String kfId = sysUser.getKfId();
        if(StringUtils.isNotEmpty(kfId)){
            SysUser kf = sysUserService.selectUserById(Long.valueOf(kfId));
            return  AjaxResult.success(kf);
        }else{
            // 查询公共客服
            SysUser  sysggkf=new SysUser();
            sysggkf.setIsGgkf("1");
            List<SysUser> sysggkfs = sysUserService.selectUserListApp(sysggkf);
            if(sysggkfs.size()>0){
                SysUser sysggkfget = sysggkfs.get(0);
                return  AjaxResult.success(sysggkfget);
            }
        }
        return  AjaxResult.success();

    }




    /**
     *
     * 修改群聊
     */
    @PostMapping("/editGroup")
    public AjaxResult editGroup(@RequestBody TGroup tGroup) {
        TGroup byId = tGroupService.getById(tGroup.getId());
        hxSevice.modifyGroup(byId.getGroupId(),tGroup);
        tGroupService.updateById(tGroup);
        return  AjaxResult.success();
    }
    /**
     *
     * 将用户移出群聊
     */
    @PostMapping("/removeMemberFromGroup")
    public AjaxResult removeMemberFromGroup(@RequestBody GroupMember  member) {
        String groupId = member.getGroupId();
        List<String> userIds = member.getUserIds();
        if(StringUtils.isEmpty(groupId)){
            return  AjaxResult.error("参数错误");
        }
        if(CollectionUtils.isEmpty(userIds)){
            return  AjaxResult.error("参数错误");
        }
        hxSevice.removeUsersFromGroup(groupId,userIds);
        QueryWrapper<GroupMember>  groupMemberQueryWrapper = new QueryWrapper<>();
        groupMemberQueryWrapper.eq("group_id",groupId);
        groupMemberQueryWrapper.in("user_id",userIds);
        groupMemberService.remove(groupMemberQueryWrapper);
        return  AjaxResult.success();
    }

    /**
     *
     * 添加用户到群聊
     */
    @PostMapping("/addMemberToGroup")
    public AjaxResult addMemberToGroup(@RequestBody GroupMember member) {
        if(member==null||StringUtils.isEmpty(member.getGroupId())){
            return  AjaxResult.error("参数错误");
        }
        if(CollectionUtils.isEmpty(member.getUserIds())){
            return  AjaxResult.error("参数错误");
        }
        this.addMemberManyToGroup(member.getGroupId(),member.getUserIds());
        return  AjaxResult.success();
    }


    public AjaxResult addMemberManyToGroup(String  groupId,  List<String> userList) {
        hxSevice.addMembersToGroup(groupId,userList);
        for (int i = 0; i < userList.size(); i++) {
            String s = userList.get(i);
            QueryWrapper<GroupMember>  groupMemberQueryWrapper = new QueryWrapper<>();
            groupMemberQueryWrapper.eq("group_id",groupId);
            groupMemberQueryWrapper.eq("user_id",s);
            if(groupMemberService.count(groupMemberQueryWrapper)==0){
                GroupMember groupMember = new GroupMember();
                groupMember.setGroupId(groupId);
                groupMember.setRole("1");
                groupMember.setUserId(s);
                groupMember.setStatus("1");
                groupMemberService.save(groupMember);
            }
        }

        return  AjaxResult.success();
    }

    public AjaxResult addMemberToGroup(String  groupId,  String userId) {
        hxSevice.addMembersToGroup(groupId,userId);
        QueryWrapper<GroupMember>  groupMemberQueryWrapper = new QueryWrapper<>();
        groupMemberQueryWrapper.eq("group_id",groupId);
        groupMemberQueryWrapper.eq("user_id",userId);
        if(groupMemberService.count(groupMemberQueryWrapper)==0){
            GroupMember groupMember = new GroupMember();
            groupMember.setGroupId(groupId);
            groupMember.setRole("1");
            groupMember.setUserId(userId);
            groupMember.setStatus("1");
            groupMemberService.save(groupMember);
        }
        return  AjaxResult.success();
    }
    /**
     *
     * 查询群成员列表(分页)
     */
    @GetMapping("/getGroupMemberlist")
    public  TableDataInfo getGroupMemberlist(GroupMember groupMember) {
        startPage();
        List<GroupMember> list = groupMemberService.selectGroupMemberList(groupMember);
        return getDataTable(list);
    }


    @Autowired
    private ITUserSfsqService tUserSfsqService;


    /**
     *
     * 担保人、代练师申请
     */
    @PostMapping("/userSfSq")
    @Transactional
    public AjaxResult userSfSq(@RequestBody TUserSfsq vo) {
        String configValue = configService.getConfigValue("dbr_sq_money");
        String type = vo.getType();
        QueryWrapper<TUserSfsq> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",SecurityUtils.getUserIdStr());
        queryWrapper.eq("type",type);
        queryWrapper.in("check_status", Arrays.asList("1","2"));
        List<TUserSfsq> listrecord = tUserSfsqService.list(queryWrapper);
        if(listrecord.size()>0){
            throw  new ServiceException("您已提交过申请");
        }
        vo.setCheckStatus("1");
        if("1".equals( type)){
            vo.setIsPay("1");
            vo.setMoney(new BigDecimal(configValue));
        }
        vo.setUserId(SecurityUtils.getUserIdStr());
        tUserSfsqService.save(vo);
        if("1".equals( type)){
            // 扣除用户余额
            BigDecimal totalMoney = tWalletService.getTotalMoney();
            if(totalMoney.compareTo(new BigDecimal(configValue))<0){
                throw  new ServiceException("余额不足");
            }
            TWallet tWallet = new TWallet();
            tWallet.setUserId(SecurityUtils.getUserIdStr());
            tWallet.setMoney(new BigDecimal(configValue).negate());
            tWallet.setType("8");
            tWalletService.save(tWallet);
        }
        return AjaxResult.success();
    }


    /**
     *
     * 获取最新的担保人、代练师申请记录
     */
    @GetMapping("/getLastSfsq")
    public   AjaxResult getLastSfsq(String type) {
        QueryWrapper<TUserSfsq> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type",type);
        queryWrapper.eq("user_id",SecurityUtils.getUserIdStr());
        queryWrapper.orderByDesc("create_time");
        List<TUserSfsq> list = tUserSfsqService.list(queryWrapper);
        if(!CollectionUtils.isEmpty(list)){
            return AjaxResult.success(list.get(0));
        }else{
            return AjaxResult.success();
        }
    }


    @Autowired
    private ITBankService tBankService;

    /**
     * 查询提现银行列表
     */
    @GetMapping("/nologin/getBanklist")
    public AjaxResult getBanklist(TBank tBank) {
        List<TBank> list = tBankService.selectTBankList(tBank);
        return AjaxResult.success(list);
    }


    @Autowired
    private ITDhService tDhService;

    /**
     * 查询君子币兑换配置列表
     */
    @GetMapping("/dhlist")
    public   AjaxResult dhlist(TDh tDh) {
        List<TDh> list = tDhService.selectTDhList(tDh);
        return AjaxResult.success(list);
    }



    /**
     * 查询余额明细列表（提现和充值记录）
     */
    @GetMapping("/getWalletlist")
    public  TableDataInfo getWalletlist(TWallet tWallet) {
        startPage();
        tWallet.setUserId(SecurityUtils.getUserIdStr());
        List<TWallet> list = tWalletService.selectTWalletList(tWallet);
        return getDataTable(list);
    }



    @Autowired
    private ITLevelService tLevelService;

    /**
     * 查询等级列表
     */
    @GetMapping("/getLevel")
    public AjaxResult getLevel(){
        // 用户的金额
        TLevel currLevel = tLevelService.getCurrLevel();
        return AjaxResult.success( currLevel);
    }




}
